package org.jslaughter.component.pickup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.nvframe.component.AbstractComponent;
import org.nvframe.component.ai.Behaviour;
import org.nvframe.component.property.PropertyManager;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.CollisionEvent;
import org.nvframe.event.eventtype.CollisionListener;
import org.nvframe.exception.NVFrameException;
import org.nvframe.manager.EntityManager;
import org.nvframe.util.settings.SettingsObj;

/**
 * 
 * @author Nik Van Looy
 *
 */
abstract class AbstractPickup extends AbstractComponent implements Pickup, CollisionListener {

	protected boolean removeOnPickup;
	protected List<String> teamsAllowed;
	
	public AbstractPickup(String id, Entity owner, SettingsObj settings) throws NVFrameException {
		super(id, owner);
		
		removeOnPickup = settings.getBoolean("removeOnPickup", true);
		teamsAllowed = settings.getList("teamsAllowed") != null ? 
				settings.getList("teamsAllowed").getStrings() : 
					new ArrayList<String> (Arrays.asList(settings.getString("teamsAllowed")));
				
		EventService.getInstance().addEventListener(this);
	}	
	
	@Override
	public void onCollision(CollisionEvent event) {
		Entity receiver = null;
		
		// determine the receiving entity
		if(event.getEntity1() == owner)
			receiver = event.getEntity2();
		else
			receiver = event.getEntity1();
		
		// static objects cannot pickup items
		if(!receiver.hasComponent(PropertyManager.class))
			return;
		
		// see if the receiver is allowed to pickup items
		Behaviour behaviour = (Behaviour) receiver.getComponent(Behaviour.class);
		if(behaviour == null || !teamsAllowed.contains(behaviour.getTeam()))
			return;

		// set the property affected by this pickup
		boolean pickedUp =  pickupAction(receiver);
		
		// remove the pickup item on collision
		if(removeOnPickup && pickedUp)
			EntityManager.getInstance().sheduleForDeletion(owner);
	}

}
